import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.*;

@WebServlet(name = "DBCServlet", value = "/DBCServlet")
public class DBCServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String loginName = request.getParameter("username");
        String loginPassword = request.getParameter("password");
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/bookshop";

        try {
            //1.加载驱动
          Class.forName(driver);
            //2.建立连接
           conn = DriverManager.getConnection(url,"root","123456");
          String sql = "select * from t_user where username=? and password=?";
          ps=conn.prepareStatement(sql);
          ps.setString(1,loginName);
          ps.setString(2,loginPassword);
          rs=ps.executeQuery();
            //3.创建语句对象
//            statement = conn.createStatement();
           //4.执行语句
//            rs = statement.executeQuery(sql);
            if (rs.next()){
                System.out.println("用户名密码正确");
            }else {
                System.out.println("用户名密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        finally {
//            try {
//                if (rs!=null)
//                    rs.close();
//            }catch (SQLException e)
//            {
//                e.printStackTrace();
//            }
//
//        }
//        if (conn!=null){
//            try {
//                conn.close();
//            }catch (SQLException e){
//                e.printStackTrace();
//            }
//        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
